package com.shelpe.services.sinbad.service.rpt;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.shelpe.services.sinbad.controller.dto.EffectDto;
import com.shelpe.services.sinbad.dao.RptCreativeMapper;
import com.shelpe.services.sinbad.entity.jpa.Creative;
import com.shelpe.services.sinbad.model.RptCreative;
import com.shelpe.services.sinbad.model.RptCreativeExample;
import com.shelpe.services.sinbad.model.RptCreativeExample.Criteria;
import com.shelpe.services.sinbad.repository.jpa.CreativeRepository;
import com.shelpe.services.sinbad.utils.DateUtil;

@Service
public class CreativeService {
	@Autowired
	private RptCreativeMapper rptCreativeMapper;
	@Autowired
	private CreativeRepository creativeRepository;

	public EffectDto creativeMetric(long creativeID, String device, String startDate, String endDate) {
		Creative po = this.creativeRepository.findOne(creativeID);
		Assert.notNull(po, "该创意不存在");
		RptCreativeExample example = new RptCreativeExample();
		Criteria criteria = example.createCriteria();
		criteria.andCreativeIdEqualTo(creativeID);
		this.setDevice(device, criteria);
		criteria.andDateBetween(DateUtil.parseDate2date(startDate), DateUtil.parseDate2date(endDate));
		RptCreative rpt = rptCreativeMapper.sumByCondition(example);

		EffectDto dto = new EffectDto();
		if (rpt != null) {
			dto.from(rpt);
		}
		return dto;
	}

	public List<EffectDto> creativeTrend(long creativeID, String device, String startDate, String endDate) {
		Creative po = this.creativeRepository.findOne(creativeID);
		Assert.notNull(po, "该创意不存在");
		RptCreativeExample example = new RptCreativeExample();
		Criteria criteria = example.createCriteria();
		criteria.andCreativeIdEqualTo(creativeID);
		this.setDevice(device, criteria);
		criteria.andDateBetween(DateUtil.parseDate2date(startDate), DateUtil.parseDate2date(endDate));
		List<RptCreative> rpts = rptCreativeMapper.selectReportsTrendByDate(example);

		List<EffectDto> dtos = new ArrayList<EffectDto>();
		if (rpts != null) {
			for (RptCreative rpt : rpts) {
				EffectDto dto = new EffectDto();
				dto.from(rpt);
				dtos.add(dto);
			}
		}
		return dtos;
	}

	private void setDevice(String device, Criteria criteria) {
		if ("pc".equals(device)) {
			criteria.andSourceBetween((byte) 1, (byte) 2);
		} else if ("mobile".equals(device)) {
			criteria.andSourceBetween((byte) 4, (byte) 5);
		} else {
			List<Byte> list = new ArrayList<Byte>();
			list.add((byte) 1);
			list.add((byte) 2);
			list.add((byte) 4);
			list.add((byte) 5);
			criteria.andSourceIn(list);
		}
	}
}
